<template>
  <div class="page-mobile-test">
    <van-tabs v-model="active" sticky @change="handleChange">
      <van-tab name="question-bank" title="题库中心">
        <div class="my-test">
          <div class="no-data" v-if="data_list.length == 0">
            <van-empty description="暂时没有课程哦~" />
          </div>
          <!-- <div class="tap-container" ref="target">
            <div
              class="tap-wrap"
              ref="tap"
              :style="{ transform: `translate3D(${left}px,0,0)` }"
            >
              <div
                :class="['tap-item', item % 2 == 0 ? 'tap-item-active' : null]"
                v-for="item in 10"
              >
                高等数学
              </div>
            </div>
          </div> -->
          <div class="card-test-box">
            <question-bank-card
              v-for="(item, index) in data_list"
              :key="index"
              :detail="item"
              :course_record_list="course_record_list"
              :type="1"
            ></question-bank-card>
          </div>
        </div>
      </van-tab>
      <van-tab name="test-center" title="试卷中心">
        <div class="no-data" v-if="data_paper_list.length == 0">
          <van-empty description="暂时没有试卷哦~" />
        </div>
        <div class="test-center" v-if="data_paper_list.length > 0">
          <div class="card-test-box">
            <test-center-card
              v-for="(item, index) in data_paper_list"
              :key="index"
              :paper_list="paper_list"
              :course_record_list="course_record_list"
              :detail="item"
            ></test-center-card>
          </div>
        </div>
      </van-tab>
      <!-- <van-tab name="wrong-note" title="错题本">
        <div class="no-data" v-if="course_record_list.length == 0">
          <van-empty description="暂时没有课程哦~" />
        </div>
        <div class="wrong-note" v-if="buy_record_list.length > 0">
          <div class="card-test-box">
            <test-card
              v-for="(item, index) in course_record_list"
              :key="index"
              :detail="item"
              :type="2"
            ></test-card>
          </div>
        </div>
      </van-tab> -->
    </van-tabs>
  </div>
</template>

<script>
import { mapState, mapActions, mapMutations } from "vuex";
import { draggable } from "~/utils/commonfun";
import QuestionBankCard from "~/components/mobile/QuestionBankCard.vue";
import TestCenterCard from "~/components/mobile/TestCenterCard.vue";
import { getAllPaper, getPaperMine, wrongQuestions } from "~/api/test";
import { getOrder, getOrderList,getAllCourseList } from "~/api/order";
export default {
  scrollToTop: true,
  components: {
    QuestionBankCard,
    TestCenterCard
  },
  // head() {
  //   return {
  //     meta: [
  //       {
  //         "http-equiv": "Content-Security-Policy",
  //         content: "upgrade-insecure-requests"
  //       }
  //     ]
  //   };
  // },
  props: ["setDisabled", "refreshFun", "setLoading"],
  data() {
    return {
      active: "question-bank",
      left: 0,
      paper_list: [], //试卷列表
      question_list:[],//题库列表
      pageSize:10,
      page:1,
      total:0,
      all_paper_list:[]

    };
  },
  computed: {
    ...mapState({
      user_info(state) {
        return state.user_info;
      },
      major_list(state) {
        return state.major_list;
      },
      buy_record_list(state) {
        return state.buy_record_list;
      },
      course_record_list(state) {
        return state.course_record_list;
      },
      is_loading(state) {
        return state.is_loading;
      },
    }),
    data_list() {
      return this.question_list;
    
    },
    data_paper_list() {
      return this.all_paper_list;
    
    },
    tap() {
      return this.$route.query.tap;
    }
  },
  
  activated() {
    
    if (process.client) {
      window.addEventListener("scroll", this.eventListener);
      if (!this.token && Object.keys(this.user_info).length == 0) {
        this.$router.replace("/m/login");
        return;
      }
    }
    if (this.tap) {
      this.active = this.tap;
    }
    this.setDisabled(false);
    this.refreshFun(() => {
      this.initTest();
      this.setLoading(false);
    });
  },
  deactivated() {
    if (process.client) {
      window.removeEventListener("scroll", this.eventListener);
    }
    this.setDisabled(true);
  },
  destroyed() {
    if (process.client) {
      window.removeEventListener("scroll", this.eventListener);
    }
  },
  watch: {
    course_record_list(new_val, old_val) {
      console.log("new_val:", new_val);
      console.log("old_val:", old_val);
      // if (new_val.length !== old_val.length) {
      //   this.getTestPapers(
      //     new_val.map(i => {
      //       return {
      //         ...i,
      //         courseId: i.id
      //       };
      //     })
      //   );
      // }
    }
  },
  methods: {
    ...mapActions(["initMajorList", "initBuyCourseRecord", "initBuyRecord"]),
    ...mapMutations(["SET_IS_LOADING", "SET_COURSE_RECORD_LIST"]),
    eventListener() {
      this.throttle(this.pullUp, 300);
    },
    throttle(fn, delay) {
      let lastTime = 0;
      return !(function () {
        let nowTime = Date.now();
        if (nowTime - lastTime > delay) {
          fn.call(this);
          lastTime = nowTime;
        }
      })();
    },
    pullUp() {
      // 滚动条离顶部的距离
      let scrollTop =
        document.documentElement.scrollTop || document.body.scrollTop;
      // 窗口可视区域高度
      let clientHeight =
        document.documentElement.clientHeight || document.body.clientHeight;
      // 滚动区域高度
      let scrollHeight =
        document.documentElement.scrollHeight || document.body.scrollHeight;
      // 滚动条 + 可视区域高度 >= 滚动条高度 ==>  滚动条触底
      // console.log(scrollTop+"+"+clientHeight+">="+scrollHeight);
      //适配处理:-120的是距离底部120px触发上拉加载，而不是触底加载
      if (scrollTop + clientHeight >= scrollHeight) {
        console.log("上拉加载1");
        console.log(this.total);
        console.log(this.question_list.length);
        if (this.total <= this.question_list.length) {
          return;
        }
        if (this.is_loading) {
          return;
        }
        this.page++;
        this.getAllCoursesMine("pullup");
        console.log("上拉加载2");
      }
    },
    async getAllCoursesMine(fetch_type) {
      this.SET_IS_LOADING(true);
      
      let result = await getAllCourseList({
        sort: "id",
        sortType: "desc",
        offset: this.pageSize * (this.page - 1),
        limit: this.pageSize,
      });
      // console.log("result:", result);
      if (result && result.data && result.data.code == 200) {
        if (fetch_type == "pullup") {
          this.question_list = [...this.question_list, ...result.data.data.rows];
        } else {
          this.question_list = result.data.data.rows;
        }
        this.total = result.data.data.rows.total;
        console.log("全部课程",result.data.data)
        // this.question_list = result.data.data.rows;
        // this.total = result.data.data.rows.total;
      } else {
        this.$Message.error("获取失败！");
        this.SET_IS_LOADING(true);
      }
    },
    async getAllTestPapers() {
      this.SET_IS_LOADING(false);
      
      let result = await getAllPaper();
      if (result && result.data && result.data.code == 200) {
        console.log("全部试卷",result.data.data);
        this.all_paper_list = result.data.data.rows;
        this.SET_IS_LOADING(false);
      } else {
        this.$Message.error("获取失败！");
        this.SET_IS_LOADING(false);
      }
    },
    handleDragMoving({ x, y, params }) {
      let left = x + params;
      let targetWidth = this.$refs.tap.offsetWidth;
      let tragWidth = this.$refs.target.offsetWidth;
      if (left < -(targetWidth - tragWidth)) {
        left = -(targetWidth - tragWidth);
      }
      if (left >= 0) {
        left = 0;
      }
      this.left = left;
    },
    async getTestPapers(buy_record_list) {
      this.SET_IS_LOADING(false);
      let params = {
        courseId: JSON.stringify(buy_record_list.map(i => i.courseId))
      };
      let result = await getPaperMine(params);
      if (result && result.data && result.data.code == 200) {
        this.paper_list = result.data.data;
        console.log("我的试卷======",this.paper_list)
        this.SET_IS_LOADING(false);
      } else {
        this.$toast("获取失败！");
        this.SET_IS_LOADING(false);
      }
    },
    async getCoursesMine() {
      this.SET_IS_LOADING(true);
      let params = {
        userId: this.user_info.id
      };
      let result = await getOrderList(params);
      if (result && result.data && result.data.code == 200) {
        this.SET_COURSE_RECORD_LIST(result.data.data);

        this.getTestPapers(
          result.data.data.map(i => {
            return {
              ...i,
              courseId: i.courseId
            };
          })
        );
      } else {
        this.$toast("获取失败！");
        this.SET_IS_LOADING(true);
      }
    },
    handleChange(name) {
      this.$router.replace({
        path: "",
        query: {
          tap: name
        }
      });
    },
    initTest() {
      if (process.client) {
        if (!this.token && Object.keys(this.user_info).length == 0) {
          this.$router.replace("/m/login");
          return;
        } else {
          this.initMajorList();
          this.getCoursesMine();
          this.getAllCoursesMine();
          this.getAllTestPapers();
          if (this.tap) {
            this.active = this.tap;
          }
        }
      }
    }
  },
  created() {
    this.setDisabled(false);
    this.initTest();
    this.refreshFun(() => {
      this.initTest();
      this.setLoading(false);
    });
  },
  mounted() {
    if (process.client) {
      window.addEventListener("scroll", this.eventListener);
    }
    this.$nextTick(() => {
      if (process.client && this.buy_record_list.length > 0) {
        // let drag_target = this.$refs.tap;
        // console.log(drag_target);
        // draggable(drag_target, {
        //   start: () => {
        //     return this.left;
        //   },
        //   moving: this.handleDragMoving
        // });
      }
    });
  }
};
</script>

<style lang="scss" scoped>
.page-mobile-test {
}
</style>
<style lang="scss">
.page-mobile-test {
  min-height: calc(100vh - 1.6rem);
  background-color: #f9f8f8;
  padding: 0 0 0.2rem 0;
  .van-sticky--fixed {
    top: 0.8rem;
  }
  .card-test-box {
  }
  .my-test {
    padding: 0.2rem 0;
    .tap-container {
      display: flex;
      align-items: center;
      width: 7.2rem;
      height: 0.8rem;
      overflow: hidden;
      .tap-wrap {
        padding: 0.1rem;
        white-space: nowrap;
        .tap-item {
          background-color: #ecebeb;
          display: inline-block;
          padding: 0.1rem 0.2rem;
          border-radius: 1rem;
          color: #101010;
          font-size: 0.22rem;
        }
        .tap-item + .tap-item {
          margin-left: 0.2rem;
        }
        .tap-item-active {
          background-color: var(--theme-color);
          color: #fff;
        }
      }
    }
  }
  .test-center {
    padding: 0.2rem 0;
  }
  .wrong-note {
    padding: 0.2rem 0;
  }
}
</style>
